/**
 * @description tabsBar标签页逻辑，如无必要请勿修改
 */
/**
   * 格式
   * {
        "path": "/index",
        "query": {},
        "params": {},
        "name": "Index",
        "parentIcon": "home-2-line",
        "meta": {
          "title": "首页",
          "icon": "home-2-line",
          "breadcrumbHidden": true,
          "noClosable": true
        },
        "index": 0
      }
  */
import { defineStore } from 'pinia'
import type { RouteLocationRaw, RouteRecordRaw } from 'vue-router'
import { router } from '@/router/index'
import { useUser } from './user'

export const useTabsStore = defineStore('tabs', {
  state: () => ({
    // tabs路由列表
    visitedRoutes: [] as RouteRecordRaw[],
    // 当前tabs路由
    currentRoute: null as RouteRecordRaw | null
  }),
  getters: {
    getVisitedRoutes: (state) =>
      state.visitedRoutes.filter((route) => route.name !== 'Login')
  },
  actions: {
    /**
     * @description 添加标签页
     * @param {*} route
     * @returns
     */
    addVisitedRoute(route) {
      const target = this.visitedRoutes.find((item) => item.path === route.path)
      if (target && !route.meta.dynamicNewTab) Object.assign(target, route)
      else if (!target) this.visitedRoutes.push(Object.assign({}, route))

      const userStore = useUser()
      if (route.meta?.iskeep) {
        userStore.addCache(route.name)
      }

      //应对极特殊情况：没有配置noClosable的情况，默认使当前tab不可关闭
      // if (!this.visitedRoutes.find((route) => route.meta.noClosable))
      //   this.visitedRoutes[0].meta.noClosable = true
    },
    /**
     * @description 删除当前标签页
     * @param {string} path
     * @returns
     */
    delVisitedRoute(path: string) {
      this.visitedRoutes = this.visitedRoutes.filter((route) => {
        if (route.path === path) {
          if (route.meta?.iskeep) {
            const userStore = useUser()
            userStore.delCache(route.name)
          }
          return false
        }
        return true
      })
    },
    /**
     * @description 删除当前标签页以外其它全部标签页
     * @param {string} path
     * @returns
     */
    delOthersVisitedRoutes(path: string) {
      this.visitedRoutes = this.visitedRoutes.filter(
        (route) => route.meta.noClosable || route.path === path
      )
    },
    /**
     * @description 删除当前标签页左边全部标签页
     * @param {string} path
     * @returns
     */
    delLeftVisitedRoutes(path: string) {
      let found = false
      this.visitedRoutes = this.visitedRoutes.filter((route) => {
        if (route.path === path) found = true
        return route.meta.noClosable || found
      })
    },
    /**
     * @description 删除当前标签页右边全部标签页
     * @param {string} path
     * @returns
     */
    delRightVisitedRoutes(path: string) {
      let found = false
      this.visitedRoutes = this.visitedRoutes.filter((route) => {
        const close: boolean = found
        if (route.path === path) found = true
        return route.meta.noClosable || !close
      })
    },
    /**
     * @description 删除全部标签页
     * @returns
     */
    delAllVisitedRoutes() {
      this.visitedRoutes = this.visitedRoutes.filter(
        (route) => route.meta.noClosable
      )
    },
    /**
     * @description 修改 meta
     * @param options
     */
    changeTabsMeta(options) {
      function handleVisitedRoutes(visitedRoutes: RouteRecordRaw[]) {
        return visitedRoutes.map((route: RouteRecordRaw) => {
          if (
            route.name === options.name ||
            route.meta?.title === options.title
          )
            Object.assign(route.meta as object, options.meta)
          if (route.children && route.children.length)
            route.children = handleVisitedRoutes(route.children)
          return route
        })
      }
      this.visitedRoutes = handleVisitedRoutes(this.visitedRoutes)
    },
    /**
     * @description: 设置当前路由
     * @param {route} route
     * @return {*}
     */
    setCurrentRoute(route: RouteRecordRaw) {
      this.currentRoute = route
    },
    /**
     * @description: tab返回上一页或者指定页
     * @param {RouteLocationRaw} routeParameter
     * @return {*}
     */
    async tabBack(routeParameter?: RouteLocationRaw) {
      const oldCurrentRoute = this.currentRoute
      // 如果routeParameter存在，跳转到指定的路由
      if (routeParameter) {
        await router.push(routeParameter)
        this.setCurrentRoute(router.currentRoute.value)
      } else {
        router.back()
        this.setCurrentRoute(router.currentRoute.value)
        // // 查找路由是否存在
        // const currentIndex = this.visitedRoutes.findIndex(
        //   (route) => route.path === this.currentRoute?.path
        // )
        // // 路由存在
        // if (currentIndex > 0) {
        //   // 如果当前路由左边有路由，就跳转到该路由左边的路由
        //   await router.push(this.visitedRoutes[currentIndex - 1].path)
        //   this.setCurrentRoute(this.visitedRoutes[currentIndex - 1])
        // } else if (currentIndex === 0) {
        //   // 如果关闭的是最左侧的路由，那么直接关闭
        //   await router.push(this.visitedRoutes[currentIndex].path)
        //   this.setCurrentRoute(this.visitedRoutes[currentIndex])
        // } else {
        //   // 否则，跳转到首页
        //   await router.push('/')
        //   this.setCurrentRoute(router.currentRoute.value)
        // }
      }
      // 删除旧的路由
      if (oldCurrentRoute && !oldCurrentRoute.meta?.noClosable)
        this.delVisitedRoute(oldCurrentRoute.path)
    }
  }
})
